#include <QQmlContext>
#include <QtQml>
#include <QDebug>
#include "ContextSetter.h"


ContextSetter::ContextSetter()
{

}

void ContextSetter::setContext(QObject *obj, QString name, QVariant value)
{
    if(!obj)
    {
        qDebug()<<__func__<<"target is Null";
    }

    auto ctx = qmlContext(obj);
    if(!ctx)
    {
        qDebug()<<__func__<<"target has no context";
    }

    ctx->setContextProperty(name,value);
}

QVariant ContextSetter::context(QObject *obj, QString name)
{
    if(!obj)
    {
        qDebug()<<__func__<<"target is Null";
    }

    auto ctx = qmlContext(obj);
    if(!ctx)
    {
        qDebug()<<__func__<<"target has no context";
    }

    return ctx->contextProperty(name);
}

void ContextSetter::setContexts(QObject *obj, QVariantMap values)
{
    if(!obj)
    {
        qDebug()<<__func__<<"target is Null";
    }

    auto ctx = qmlContext(obj);
    if(!ctx)
    {
        qDebug()<<__func__<<"target has no context";
    }

    QList<QQmlContext::PropertyPair> props;

    for(const auto &i:values.keys())
    {
        props << QQmlContext::PropertyPair{i,values.value(i)};
    }

    ctx->setContextProperties(props);
}
